package com.wangshuqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/uploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("GBK");
        // 这种文件上传方式，正常操作可以运行，但是误操作的话会报异常
        // 1. 单文件上传
        /*Part part = request.getPart("file1");
        part.write(getFilePath(part));
        PrintWriter writer = response.getWriter();
        writer.write(request.getParameter("fileID") + " 文件上传成功");
        writer.flush();
        writer.close();*/

        // 2. 多文件上传
        Collection<Part> parts = request.getParts();
        if (parts == null || parts.size() == 0) {
            response.getWriter().write(request.getParameter("fileID") + " 请填写参数");
        }
        for (Part part : parts) {
            if (part.getName().startsWith("upload")) {
                part.write(getFilePath(part));
            }
        }
        PrintWriter writer = response.getWriter();
        writer.write(request.getParameter("fileID") + " 文件上传成功");
        writer.flush();
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 获取文件上传绝对路径
     *
     * @param part
     * @return java.lang.String
     * @author codewsq
     * @date 2021/8/8 0008 14:16
     */
    public String getFilePath(Part part) {
        String realPath = this.getServletContext().getRealPath("/WEB-INF/upload/");
        String header = part.getHeader("content-disposition");
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] split = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] split2 = split[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        String fileName = split2[1].substring(split2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
        File file = new File(realPath, UUID.randomUUID() + fileName);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getAbsolutePath();
    }
}
